(function($){
	
        var options = {
            downUrl:['https://mmbiz.qpic.cn/'],//微信不能信息的地址需要服务器下载图片
            fetchUrl:"/upload/fetch",//替换图片接口
            uploadUrl:"/upload/file",//上传地址
            qnToken:"/upload/token",//请求七牛token
            qn:true//开启七牛上传
            	
        };

        var updateContent = function(that,viewObj){
            $(that).html(viewObj.html());
        }

        //向七牛上传图片
        var putb64 =function(pic, size, fileName, success){
        	var name = window.btoa(fileName);
        	pic = pic.split("base64,")[1];
            var url = "http://upload.qiniu.com/putb64/"+size+"/key/"+name; //非华东空间需要根据注意事项 1 修改上传域名
            var xhr = new XMLHttpRequest();
            
            var qiniuUrl = "";
            xhr.onreadystatechange=function(){
              if (xhr.readyState==4){
            	  success(qiniuUrl+fileName);
              }
            }
            xhr.open("POST", url, true);
            xhr.setRequestHeader("Content-Type", "application/octet-stream");
            
            $.ajax({url:options.qnToken, dataType: "json",success:function(token){
            	xhr.setRequestHeader("Authorization", "UpToken "+token.uptoken);
            	qiniuUrl = token.qiniuUrl;
                xhr.send(pic);
            }})
            
        }
        var imgTools;
        //上传图片或视频
        var uploadData = function(imgthat, opt){
        	imgTools.find("	[type='file']").change(function(e) {
    			var files = e.target.files;
    			if(window.FileReader){
    				$.each(files, function(i,file){
    					var reader = new FileReader();
    					reader.readAsDataURL(file);
    					reader.onload = function(evt){
    						var fext = (file.name.split(".").length >0?file.name.split(".")[file.name.split(".").length-1]:'')
    						if(fext == 'mp4'){
    							var video = $('<video src="'+URL.createObjectURL(file)+'" controls></video>');
    							video[0].onloadedmetadata = function () {
    								var width = this.videoWidth;
    								var height = this.videoHeight;
    								var fileNme = new Date().getTime() +"_wh"+width+"x"+height+"."+fext;
    								var load = $('<div style="position: absolute;"><div class="upload-loadbox"></div><div class="upload-load"></div><div class="upload-text">上传中...</div></div>');
    								if(opt.qn){
    									putb64(evt.target.result, file.size, fileNme, function(path){
    										load.remove();
    									});
    								}else {
    									$.ajax({url:opt.uploadUrl, type:"post", data:{baseDateURL: evt.target.result, name:fileNme}, success:function(ret){
    										if(ret.success){
    											load.remove();
    										}
    									}});
    								}
    								
    							};
    						} else{
    							var image = new Image();  
    							image.src = URL.createObjectURL(file);
    							image.onload = function(){
    								var width = image.width;
    								var height = image.height;
    								var fileNme = new Date().getTime() +"_wh"+width+"x"+height+"."+fext;
    								var load = $('<div style="position: absolute;"><div class="upload-loadbox" style="width:'+(opt.width-2)+'px;height:'+(opt.height-2)+'px"></div><div class="upload-load" style="margin:'+(opt.height/2-12)+'px '+(opt.width/2-12)+'px"></div><div class="upload-text" style="margin:'+(opt.height/2+15)+'px 0px 0px '+(opt.width/2-28)+'px">上传中...</div></div>');
    								if(opt.qn){
    									putb64(evt.target.result, file.size, fileNme, function(path){
    										$(imgthat).attr("src", path)
    										load.remove();
    									});
    								} else {
    									$.ajax({url:opt.uploadUrl, type:"post", data:{baseDateURL: evt.target.result, name:fileNme}, success:function(ret){
    										if(ret.success){
    											$(imgthat).attr("src", ret.obj.path)
    											load.remove();
    										}
    									}});
    								}
    							};
    						}
    					}
    				})
    			}
    		});
        }
        
        
        var number = 0;
        var main = function(that, opt){
        	$(that).hide();
            var viewObj = $('<div contenteditable="true" style="overflow: auto;cursor: text;height: 300px;border: solid 1px #d9d9d9;width:500px;padding:5px; 0px;"></div>')
            if($(that).val()!=''){
            	viewObj.html($(that).val());
            }
            viewObj.on("blur", function(){
            	$(that).val(viewObj.html());
            	//+'<style>*{padding: 0px;margin: 0px}body{font-family: "Microsoft YaHei",-apple-system-font,"Helvetica Neue","PingFang SC","Hiragino Sans GB",sans-serif;line-height: inherit;}body img {height: auto !important;}</style>'
            });
            //图片动态绑定，手动修改图片
            viewObj.on("click","img", function(e){
            	var imgthat = this;
            	if(imgTools != null){
            		imgTools.remove();
            	} 
            	var top = $(imgthat).offset().top;
            	var left = $(imgthat).offset().left;
            	imgTools = $('<div class="fb-tools"><div class="fb-tools-row"><span class="fb-tools-item" id="fb-tools-item1">替换图片</span><input type="file" multiple="true" accept="image/*" style="display: none;"/></div></div>')
            	$("body").append(imgTools);
            	var imgToolsH = imgTools.height();
            	imgTools.css("top", e.pageY-imgToolsH-10);
            	imgTools.css("left", left);
            	//替换图片
            	imgTools.find("#fb-tools-item1").click(function(){
            		imgTools.find("input[type='file']").click();
            	});
            	uploadData(imgthat, opt);
            });
            viewObj.scroll(function() {
            	if(imgTools != null){
            		imgTools.remove();
            	}
            });
            var body = viewObj.get(0);
            body.addEventListener("keyup", function (e){
                var code = e.keyCode || e.which;
                if(code == 91 || code == 86 || code ==8){
                    viewObj.find("img").css("max-width", "100%");
                    viewObj.find("img").attr("_moz_resizing", "true");
                    
                    $.each(opt.downUrl, function(i,url){
                        viewObj.find("img[src^='"+url+"']").each(function(){
                        	var datetime = new Date().getTime();
                        	var imgthat = this;
                            var oldsrc =$(this).attr("src");
                            number++;
                            $.ajax({url:opt.fetchUrl,data:{url:oldsrc,key:"formbuilder_"+datetime+"_"+number}, dataType: "json",success:function(ret){
                            	$(imgthat).attr("src", ret.newUrl)
                            }});
                        });
                        viewObj.find("section").css({"background-image^":'url("'+url}).each(function(){
                        	var imgUrl = $(this).css('background-image');
                    		if(imgUrl.indexOf('url("'+url) == 0){
                    			var oldsrc = imgUrl.replace('url("', '').replace('")', '');
                    			var datetime = new Date().getTime();
                            	var imgthat = this;
                                number++;
                                $.ajax({url:opt.fetchUrl,data:{url:oldsrc,key:"formbuilder_"+datetime+"_"+number}, dataType: "json",success:function(ret){
                                	$(imgthat).css('background-image', 'url("'+ret.newUrl+'")');
                                }});
                    		}
                        });
                        
                        
                    });
                    //viewObj.blur();
                    //$(that).val(viewObj.html());
                }
            });
            
            var mainObj = $('<div><div style="border: #f1f1f1 solid 1px;padding: 0px 10px;color: #d9d9d9;">友情提示：请在微信编辑器编辑后复制粘贴上面</dvi></div>');
            mainObj.prepend(viewObj);
            mainObj.insertAfter($(that))
        }

        $.fn.extend({
            jjformBuilder:function(opt){
                var opt2 = $.extend({}, options, opt||{});
                this.each(function(){
                    main(this, opt2);
                });
            }
        });
    })(jQuery);
